package com.dobest.securitydemo.service.impl;

import com.dobest.securitydemo.dao.RoleRepository;
import com.dobest.securitydemo.dao.UserRepository;
import com.dobest.securitydemo.model.domain.Role;
import com.dobest.securitydemo.model.domain.User;
import com.dobest.securitydemo.model.vo.UserDetail;
import com.dobest.securitydemo.service.IUserService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author hujiansong
 * @mail 1358199510@qq.com
 * @since 2018/7/17 15:46
 */
@Service
public class UserServiceImpl implements IUserService {

    private static final String AUTH_SPILIT = "|";

    @Autowired
    UserRepository userRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    ModelMapper modelMapper;

    @Override
    public UserDetail findUserDetailByUserName(String username) {
        User user = userRepository.findUserByUsername(username);
        if (user == null) {
            return null;
        }
        UserDetail userDetail = modelMapper.map(user, UserDetail.class);
        Role role = roleRepository.findOne(user.getRoleId());
        if (role != null) {
            userDetail.setRole(role);
            Collection<? extends GrantedAuthority> authorities;
            authorities = spliteAuth(role);
            userDetail.setAuthorities(authorities);
        }
        return userDetail;
    }

    private Collection<? extends GrantedAuthority> spliteAuth(Role role) {
        Collection<GrantedAuthority> authorities = new HashSet<>();
        String auth = role.getAuth();
        if(!StringUtils.isEmpty(auth)){
            String[] authArr = auth.split(AUTH_SPILIT);
            for (String authStr : authArr) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authStr);
                authorities.add(grantedAuthority);
            }
        }
        return authorities;
    }
}
